package com.beiye.drivertransport.utils;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.util.Log;
import android.widget.EditText;

import com.alibaba.fastjson.JSON;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.android.frame.http.HttpListener;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.bean.WriterBean;
import com.beiye.drivertransport.http.Login;
import com.beiye.drivertransport.thirdparty.oss.OSSConfig;
import com.beiye.drivertransport.thirdparty.oss.OSSUpFileListener;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by ky on 2018/1/15.
 */

public class HelpUtil {
    /**
     * 根据图片路径获取本地图片的Bitmap
     *
     * @param url
     * @return
     */
    public static Bitmap getBitmapByUrl(String url) {
        FileInputStream fis = null;
        Bitmap bitmap = null;
        try {
            fis = new FileInputStream(url);
            bitmap = BitmapFactory.decodeStream(fis);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            bitmap = null;
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                fis = null;
            }
        }

        return bitmap;
    }

    /**
     * bitmap旋转90度
     *
     * @param bitmap
     * @return
     */
    public static Bitmap createRotateBitmap(Bitmap bitmap) {
        if (bitmap != null) {
            Matrix m = new Matrix();
            try {
                m.setRotate(90, bitmap.getWidth() / 2, bitmap.getHeight() / 2);// 90就是我们需要选择的90度
                Bitmap bmp2 = Bitmap.createBitmap(bitmap, 0, 0,
                        bitmap.getWidth(), bitmap.getHeight(), m, true);
                bitmap.recycle();
                bitmap = bmp2;
            } catch (Exception ex) {
                System.out.print("创建图片失败！" + ex);
            }
        }
        return bitmap;
    }

    public static Bitmap getBitmapByUri(Uri uri, ContentResolver cr){
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(cr
                    .openInputStream(uri));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            bitmap = null;
        }
        return bitmap;
    }

    /**
     * 获取格式化日期字符串
     * @param date
     * @return
     */
    @SuppressLint("SimpleDateFormat")
    public static String getDateFormatString(Date date) {
        if (date == null)
            date = new Date();
        String formatStr = new String();
        SimpleDateFormat matter = new SimpleDateFormat("yyyyMMdd_HHmmss");
        formatStr = matter.format(date);
        return formatStr;
    }


    public static void uploadFile(Context context, File file, int type, OSSUpFileListener ossUpFileListener){
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        String userId = data.getUserId();//从新获取最新finish.
        new Login().writer(userId, type+"", file.getName(), new HttpListener() {
            @Override
            public void onSuccess(String result, Call call, Response response, int what) {
                LogUtils.e("测试", "onSuccess: "+result );

                WriterBean writerBean= JSON.parseObject(result,WriterBean.class);
                WriterBean.DataBean dataBean=writerBean.getData();

                OSSConfig config=new OSSConfig(context,dataBean.getEndPoint(),dataBean.getAccessKeyId(),dataBean.getAccessKeySecret(),dataBean.getSecurityToken());
                PutObjectRequest put = new PutObjectRequest(dataBean.getBucketName(),dataBean.getObjectName(),file.getAbsolutePath());
                OSSAsyncTask task = config.getOss().asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                    @Override
                    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                        ossUpFileListener.onSuccess(writerBean);
                        LogUtils.e("测试", "onSuccess: "+writerBean.getData().getObjectAcsUrl() );
                    }
                    @Override
                    public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                        // 请求异常。
                        if (clientExcepion != null) {
                            // 本地异常，如网络异常等。
                            clientExcepion.printStackTrace();
                            ossUpFileListener.onFail("本地网络异常",writerBean);
                        }
                        if (serviceException != null) {
                            // 服务异常。
                            LogUtils.e("ErrorCode", serviceException.getErrorCode());
                            LogUtils.e("RequestId", serviceException.getRequestId());
                            LogUtils.e("HostId", serviceException.getHostId());
                            LogUtils.e("RawMessage", serviceException.getRawMessage());
                            ossUpFileListener.onFail("服务异常",writerBean);
                        }
                        ossUpFileListener.onFail("上传失败",writerBean);
                        LogUtils.e("测试", "onFailure: "+serviceException.getRawMessage()+" "+clientExcepion.getMessage());
                    }
                });
            }

            @Override
            public void onError(String result, Call call, Response response, int what) {
                LogUtils.e("测试", "onError: "+result );
            }

            @Override
            public void onParseFail() {

            }

            @Override
            public void onFailure(Call call, int what) {

            }
        }, 10);
    }


    public static boolean unRealName(String str){
        Pattern p = Pattern.compile("[^\u4e00-\u9fa5·]");
        Matcher m = p.matcher(str);
        return m.find();
    }

    public static Bitmap returnBitMap(String url){
        URL myFileUrl = null;
        Bitmap bitmap = null;
        try {
            myFileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public static Bitmap getBitmap(Context context, int vectorDrawableId) {
        Bitmap bitmap = null;
        int WX_THUMB_SIZE = 120;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            Drawable vectorDrawable = context.getDrawable(vectorDrawableId);
            bitmap = Bitmap.createBitmap(WX_THUMB_SIZE, WX_THUMB_SIZE, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
            vectorDrawable.draw(canvas);
        } else {
            bitmap = BitmapFactory.decodeResource(context.getResources(), vectorDrawableId);
        }
        return bitmap;
    }

    public static String judgeStrNull(Object str) {
        return (str == null) ? "" : str + "";
    }
    public static int judgeIntNull(Object str) {
        return (str == null) ? 0 : (int)str;
    }

    //弹窗提示
    public static void showTiShiDialog(Context context,String msg){
        TiShiDialog.Builder builder1 = new TiShiDialog.Builder(context);
        builder1.setMessage(msg);
        builder1.setTitle("提示:");
        builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder1.create().show();
    }


    public static String getNewMac() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return null;
                }

                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }

                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static void setUnEditAble(List<EditText> lists){
        for(EditText editText:lists){
            editText.setFocusable(false);
            editText.setFocusableInTouchMode(false);
        }
    }

    public static String getTime(Date date,String dateStype) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat(dateStype);
        return format.format(date);
    }
}
